package com.bjpowernode.filter;
import com.bjpowernode.beans.User;
import com.bjpowernode.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class MyLoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {

        String requestURI = req.getRequestURI();
        System.out.println("正在过滤【"+requestURI+"】页面");
        //在没有spring的情况下使用HttpServletRequest对象获取
        HttpSession session = req.getSession();
        //判断是否登录
        User login =(User) session.getAttribute("user");
        if(login==null){
            System.out.println("过滤器正在试图通过cookies登录（自定登录）");
            //回去
            //看看有没有cookies【获取cookies】
            Cookie[] cookies = req.getCookies();
            String loginAct="";
            String loginPwd="";

            //cookies如果是空的，直接登录失败
            if(cookies==null){
                res.sendRedirect("/static/login.html");
                return;
            }

            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("loginAct")){
                    loginAct=cookie.getValue();
                }
                if(cookie.getName().equals("loginPwd")){
                    loginPwd=cookie.getValue();
                }
            }
            //使用业务查找用户是否存在
            ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
            UserServices userServices = context.getBean("userServicesFilter",UserServices.class);
            User loginTemp = userServices.login(loginAct, loginPwd);
            if(loginTemp==null){
                res.sendRedirect("/static/login.html");
                return;
            }
            else{
                //自定登录成功，则把用户放到session里面
                session.setAttribute("user",loginTemp);
                //放行
                chain.doFilter(req,res);
            }
        }
        else{
            //放行
            chain.doFilter(req,res);
        }

    }
}
